﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Nirvana
{
    public sealed class AudioClipCache
    {
        private AudioClip audioClip;
        private float defaultReleaseAfterFree = 30f;
        private float lastFreeTime = -1f;
        private Dictionary<AudioClip, AudioClipCache> audioClipCacheMap;
        public AssetID AssetID { get; private set; }
        public int ReferenceCount { get; private set; }
        public float LastFreeTime
        {
            get { return lastFreeTime; }
        }
        public float ReleaseAfterFree { get; private set; }
        public string Error { get; private set; }

        public AudioClipCache(AssetID asset, Dictionary<AudioClip, AudioClipCache> map)
        {
            this.AssetID = asset;
            this.audioClipCacheMap = map;
        }

        public void SetReleaseTimeAfterFree(float t)
        {
            this.defaultReleaseAfterFree = t;
            this.ReleaseAfterFree = t;
        }

        public void Retain()
        {
            ReferenceCount++;
        }
        public void Release()
        {
            ReferenceCount--;
            lastFreeTime = Time.realtimeSinceStartup;
        }

        public bool IsNotNull()
        {
            return this.audioClip != null;
        }
        public AudioClip GetObject()
        {
            return this.audioClip;
        }

        public void Load(AssetID assetid)
        {
            this.AssetID = assetid;
            AssetManager.LoadObjectSync(this.AssetID, typeof(AudioClip),  (t)=>
            {
                if (t == null)
                {
                    this.Error = string.Format("The asset {0} is not a AudioClip.", AssetID);
                    return;
                }
                this.audioClip = t as AudioClip;

                ReleaseAfterFree = defaultReleaseAfterFree;

                if (audioClipCacheMap.ContainsKey(this.audioClip))
                {
                    Debug.LogWarningFormat("The AudioClip {0} has been loaded.", AssetID);
                    this.audioClipCacheMap[this.audioClip] = this;
                }
                else
                {
                    this.audioClipCacheMap.Add(this.audioClip, this);
                }
            });
        }

    }
}
